package demo2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LeetCode18 {
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> lists = new ArrayList<>();
        Arrays.sort(nums);
        int n = nums.length;
        for(int  i = 0; i < n; ) {
            int a = nums[i];
            for(int j = i + 1; j < n; ) {
                int b = nums[j];
                long c = (long)target - (a + b);
                int left = j + 1, right = n - 1;
                while(left < right) {
                    if(nums[left] + nums[right] < c) left++;
                    else if(nums[left] + nums[right] > c) right--;
                    else {
//                        List<Integer> list = new ArrayList<>();
//                        list.add(a);
//                        list.add(b);
//                        list.add(nums[left]);
//                        list.add(nums[right]);
//                        lists.add(list);
//                        left++; right--;
                        lists.add(Arrays.asList(a,b,nums[left++],nums[right--]));
                        while(left < right && nums[left] == nums[left - 1]) left++;
                        while(left < right && nums[right] == nums[right + 1]) right--;
                    }
                }
                j++;
                while(j < n && nums[j] == nums[j - 1]) j++;
            }
            i++;
            while(i < n && nums[i] == nums[i - 1]) i++;
        }
        return lists;
    }


    public static void main(String[] args) {
        int[] arr = new int[]{1000000000,1000000000,1000000000,1000000000};
        int target = -294967296;
        List<List<Integer>> lists = new ArrayList<>();
        lists = fourSum(arr,target);
        System.out.println(lists);
    }
}
